const Koa = require('koa');
const router = require('koa-router')();
const static = require('koa-static');
const fs = require('fs');
const path = require('path');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
const jwt = require('koa-jwt');
const checkToken = require('./token/checkToken');
// const Store = require('./redis/Store');
// const session = require('koa-session2');
const { connect,initSchemas } = require('./database/init');
// 路由导入
const userRouter = require('./route/user');
const globalRouter = require('./route/global');
const goodsRouter = require('./route/goods');
const uploadRouter = require('./route/upload');
app.use(static(path.join(__dirname,'./public')));
app.use(bodyParser());
// 数据库
const cert = fs.readFileSync(path.join(__dirname, './rsa/rsa_public_key.pem'));
;(async () => {
  await connect();
  initSchemas();
})()

// post请求获取参数原理
const parsePostData= (ctx) => {
  return new Promise((resolve,reject) => {
    try{
      let postdata = "";
      ctx.req.addListener('data', (data) => {
        postdata += data;
      })
      ctx.req.addListener('end', () => {
        let parseData = parseQueryStr( postdata )
        resolve(parseData);
      })
    } catch (err) {
      reject(err);
    }
  })
}

const parseQueryStr = (queryStr) => {
  let queryData = {};
  let queryStrList = queryStr.split('&');
  console.log(queryStrList);
  for(let [index, queryStr] of queryStrList.entries()) {
    let itemList = queryStr.split('=');
    queryData[itemList[0]] = decodeURIComponent(itemList[1])
  }
  return queryData;
}
// app.use(ctx => {
//   ctx.body = 'Hello koa';
// });

router.post('/postbody', (ctx,next)=> {
  ctx.body=ctx.request.body;
  next();
});



router.post('/post', async (ctx,next) => {
  let postData = await parsePostData(ctx);
  console.log(postData);
  ctx.body = {
    ...parsePostData
  }
  console.log('第一步')
  next();
})

// 中间件就是匹配路由之前或者匹配路由完成做的一系列的操作，我们就可以把它叫做中间件。
// 应用级中间件
app.use(async (ctx,next) => {
  console.log(new Date());
  await next();
})

// 路由中间件
router.get('/', (ctx,next) => {
  console.log("进入主页");
  next();
})

// app.use(async (ctx,next) => {
//   if(ctx.method === 'POST') {
//     let postData = await parsePostData(ctx);
//     ctx.body = postData;
//   }
//   next();
// })

// 错误处理中间件
app.use(async (ctx,next) => {
  if(ctx.status == 404) {
    ctx.status = 404;
    ctx.body="页面未找到"
  }
  await next();
})

app.use((ctx,next) => {
  return next().catch(err => {
    if(401 == err.status) {
      ctx.status=401;
      ctx.body=err.name;
    } else {
      throw err;
    }
  })
})
// 第三方中间件
router.get('/', (ctx,next) => {
  ctx.body="hello koa";
})

router.get('/list', (ctx,next) => {
  ctx.body="列表页"
});

router.get('/content',(ctx,next) => {
  let url = ctx.url;

  let request = ctx.request;
  let req_query = request.query;
  let req_querystring = request.querystring;

  let ctx_query = ctx.query;
  let ctx_querystring = ctx.querystring;
  ctx.body = {
    url,
    req_query,
    req_querystring,
    ctx_query,
    ctx_querystring
  }
})


router.get('/product/:proid',(ctx,next) => {
  ctx.body = {
    id: ctx.params,
    reqid: ctx.request.params
  }
})

router.use('/users',userRouter.routes());
// /global/menu
router.use('/global',globalRouter.routes());
// goods
router.use('/goods',goodsRouter.routes());
// upload
router.use('/upload',uploadRouter.routes());
// 使用redis作为session存储
// app.use(session({
//   store: new Store(),
//   key: "SESSIONID",  // default "koa:sess"
// }));
console.log(cert);
app.use(jwt({ secret: cert, isRevoked: checkToken, algorithms: ['RS256'] }).unless({ path: [/^\/users/, /^\/goods/, /^\/upload/,/^\/public/, /^\/$/,] }))
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000,() =>{console.log("open http://localhost:3000")});
